import axios from "axios";
import qs from "qs";
import { ElMessage } from "element-plus";

// 创建 axios 实例
const service = axios.create({
  baseURL: '/api',
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
  paramsSerializer: (params) => qs.stringify(params),
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    //从localStorage中取出accessToken
    //const accessToken = getAccessToken();
    //config.headers.Authorization = `Bearer ${accessToken}`;
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { flag, data, msg } = response.data;
    if (flag == true) {
      return data;
    }
    ElMessage.error(msg || "系统出错");
    return Promise.reject(new Error(msg || "Error"));
  },
  async (error) => {
    console.error("request error", error); // for debug
    const { config, response } = error;
    if (response) {
      const { code, msg } = response.data;
      ElMessage.error(msg || "系统出错");
    }
    return Promise.reject(error.message);
  }
);

export default service;